package com.qhx.common.util;

import com.qhx.common.annotation.NotEmpty;
import com.qhx.common.domain.BaseEntity;
import lombok.extern.slf4j.Slf4j;

import java.lang.reflect.Field;



@Slf4j
public class NotEmptyUtil
{


    public static String checkEmptyFiled(Object obj,String ...fileNames)
    {
        return  checkEmptyFiled(obj,obj.getClass(),fileNames);
    }

    
    public static String checkEmptyFiled(Object obj,Class<?> cls,String ...fileNames)
    {
        NotEmpty notEmptyCls = cls.getAnnotation(NotEmpty.class); 
        Field[] fields = cls.getDeclaredFields();
        for (Field field : fields)
        {
            field.setAccessible(true);
            try
            {
                
                String fileName = field.getName();
                if(StringUtil.equalsAny(fileName,fileNames))
                {
                   continue;
                }
                
                Object value = field.get(obj);
                
                if(StringUtil.isEmpty(value))
                {
                    String end = checkFileIsAn(field); 
                    if(end != null)
                    {
                        return end;
                    }
                    if(notEmptyCls != null && notEmptyCls.required()){ 
                        return fileName + "不能为空";
                    }
                }
                
                if(value instanceof  String){
                   if(StringUtil.isEmpty(value.toString()))
                   {
                       String end = checkFileIsAn(field); 
                       if(end  != null)
                       {
                           return end;
                       }
                       if(notEmptyCls != null && notEmptyCls.required()){ 
                           return fileName + "不能为空";
                       }
                   }
                }
                
                
                
                
                
                
                
                

            } catch (IllegalAccessException e)
            {
                log.error("读取字段异常:"+e.getMessage());
                return null;
            } catch (Exception e)
            {
               log.error(e.getMessage());
            }
        }
        if(cls.getSuperclass() == BaseEntity.class || cls.getSuperclass() == Object.class) 
        {
            return null;
        }
        return  checkEmptyFiled(obj,cls.getSuperclass(),fileNames);
    }


    private static String checkFileIsAn(Field field)
    {
        NotEmpty verifyField = field.getAnnotation(NotEmpty.class);
        if (verifyField != null && verifyField.required()){
            if(StringUtil.isEmpty(verifyField.extra()))
            {
                return field.getName() + "不能为空！";
            }
            return verifyField.extra() + "不能为空！" ;
        }
        return null;
    }




}
